package com.sec.history.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.sec.base.utils.AjaxJson;
import com.sec.history.dao.HistoryDao;
import com.sec.history.entity.History;
import com.sec.history.service.HistoryService;
import com.sec.user.entity.User;

@Service("historyService")
public class HistoryServiceImpl implements HistoryService {

	@Autowired
	private HistoryDao historyDao;

	@Override
	public void saveHistory(History history) {
		historyDao.save(history);
	}

	@Override
	public AjaxJson findHistoryListByPage(HttpServletRequest request, int pageNumber, int pageSize) {
		AjaxJson j = new AjaxJson();
		j.setCode("failure");
		j.setMsg("获取分页数据失败");
		try {
			User user = (User) request.getSession().getAttribute("user");
			if (user == null) {
				j.setMsg("请登录");
				return j;
			}
			Pageable pageable = PageRequest.of(pageNumber - 1, pageSize);
			Page<History> page = historyDao.findAllByUser(user, pageable);
			Map<String, Object> pagaData = new HashMap<>();
			pagaData.put("historyList", page.getContent());
			pagaData.put("count", page.getTotalElements());
			j.setData(pagaData);
			j.setCode("success");
			j.setMsg("获取分页数据成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return j;
	}

	@Override
	public AjaxJson getHistroyInfo(String id) {
		AjaxJson j = new AjaxJson();
		j.setCode("failure");
		j.setMsg("获取历时数据失败");
		try {
			Optional<History> optional = historyDao.findById(id);
			if (optional.isPresent()) {
				j.setCode("success");
				j.setMsg("获取历时数据成功");
				j.setData(optional.get());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return j;
	}

}
